﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace winform_demo._4_自定义控件与用户控件.demo
{
    /*
     * 变色按钮的扩展功能：
     * 1. 可设置状态，状态定义：0：未按下   1：已按下   -1：无状态或状态无效
     * 2. 可设置不同状态下的按钮背景图片或背景颜色（如果同时设置了两个，已背景图片为优先）
     * 3. 按钮切换状态时自动切换背景图片或背景颜色
     */
    public class MyButton:Button
    {
        public delegate void StateChangedEventHandler(int state);
        public event StateChangedEventHandler StateChanged;

        private int state = 0;

        public int State
        {
            set
            {
                if (value != state)
                {
                    state = value;
                    SetState(state);
                    StateChanged?.Invoke(state);
                }
            }
            get { return state; }
        }
        public Image PressedImage { get; set; }
        public Image UnpressedImage { get; set; }
        public Color PressedColor { get; set; } = SystemColors.ControlDark;
        public Color UnpressedColor { get; set; } = SystemColors.Control;

        public MyButton()
        {
            this.Click += MyButton_Click;
        }

        private void MyButton_Click(object sender, EventArgs e)
        {
            if (state == 0)  //如果当前状态为未按下，要转换为已按下状态
            {
                State = 1;
            }
            else if(state == 1)
            {
                State = 0;
            }
        }

        private void SetState(int state)
        {
            if (state == 0)
            {
                if (PressedImage != null)
                {
                    this.BackgroundImage = UnpressedImage;
                }
                else
                {
                    this.BackgroundImage = null;
                    this.BackColor = UnpressedColor;
                }
            }
            else if (state == 1)
            {
                if (PressedImage != null) //如果有设置的按下时的背景图片，则优先使用该图片
                {
                    this.BackgroundImage = PressedImage;
                }
                else //否则使用默认的背景颜色
                {
                    this.BackgroundImage = null;
                    this.BackColor = PressedColor;
                }
            }
        }
    }
}
